<style scoped>
</style>
<template>
  <div>
    <Modal
      v-model="IsModalShow"
      :title="modalFormTitle"
      :mask-closable="false"
      @on-cancel="cancel"
      width="1000"
    >
      <Tabs value="name1">
        <TabPane
          label="基本信息"
          name="name1"
        >
          <Form
            ref="modalForm"
            :model="modalForm"
            :label-width="120"
            value=true
            style="padding: 3px 60px"
          >
            <Row>
              <Col span="12">
              <Form-item
                label="子单位名称"
                prop="name"
                :rules="{required: true, message: '必填',min:1,max:10, trigger:'blur',type:'string'}"
              >
                <Input v-model="modalForm.name"></Input>
              </Form-item>
              <Form-item
                label="地址"
                prop="addr"
                :rules="{required: true, message: '必填', trigger:'blur',type:'string'}"
              >
                <Input v-model="modalForm.addr"></Input>
              </Form-item>

              <Form-item
                label="负责人姓名"
                prop="managerName"
                :rules="{required: true, message: '必填', trigger:'blur',type:'string'}"
              >
                <Input v-model="modalForm.managerName"></Input>
              </Form-item>

              <Form-item
                label="负责人电话"
                prop="managerMobile"
                :rules="{required: true, message: '输入11位手机号', trigger:'blur',type:'string',pattern: /^1\d{10}$/}"
              >
                <Input v-model="modalForm.managerMobile"></Input>
              </Form-item>
              <Form-item label="联网单位">
                <Cascader
                  v-model="modalForm.areaGcbd"
                  :data="areaGcbdData"
                  :filterable="true"
                  transfer
                ></Cascader>
              </Form-item>
              <Form-item
                label="微信名称"
                prop="wxName"
              >
                <Input
                  v-model="modalForm.wxName"
                  :readonly="true"
                ></Input>
              </Form-item>
              <Form-item
                label="微信头像"
                prop="wxImage"
              >
                <img
                  :src="modalForm.wxImage"
                  style="width:50px"
                />
              </Form-item>
              <Form-item
                label="责任书"
                prop="dutyLetter"
              >
                <img
                  :src="baseServerUrl+modalForm.dutyLetter"
                  style="width:50px"
                />
              </Form-item>
              </Col>
              <Col
                span="11"
                offset="1"
              >
              <Input
                v-model="addrSearchVal"
                element-id='tipinput'
              >
              <span slot="prepend">请输入地址</span>
              <Button
                slot="append"
                icon="ios-search"
                @click="searchAddr"
              ></Button>
              </Input>
              <div style="position:relative;margin-bottom:10px;margin-top:10px;">

                <div id='map-container'>

                </div>
                <div
                  id="mapShade"
                  :style="{'display':mapShadeShow?'block':'none'}"
                ></div>
              </div>

              <Row>
                <Col span="10">
                <Form-item
                  label="经度"
                  label-width="60"
                >
                  <Input v-model="modalForm.lat"></Input>
                </Form-item>
                </Col>
                <Col span="10">
                <Form-item
                  label="纬度"
                  label-width="60"
                >
                  <Input v-model="modalForm.lng"></Input>
                </Form-item>
                </Col>
                <Col
                  span="3"
                  offset="1"
                >
                <Button
                  type="warning"
                  :loading="modalForm_loading"
                  @click="startLocate"
                >设置地址</Button>
                </Col>
              </Row>

              </Col>
            </Row>

          </Form>
        </TabPane>
        <TabPane
          label="紧急联系人"
          name="name2"
        >
          <div style="padding:10px 100px;">
            <Row style="padding:10px 50px;">
              <Button
                type="warning"
                icon="plus-round"
                @click="addNotifier"
              >添加紧急联系人</Button>
            </Row>

            <Form
              :model="formItem"
              :label-width="50"
            >
              <Row
                v-if="alarmNotifierList.length>0"
                v-for="(item,index) in alarmNotifierList"
                :key="index"
              >
                <Col span=12>
                <FormItem label="姓名">
                  <Input v-model="item.name"></Input>
                </FormItem>
                </Col>
                <Col span=12>
                <FormItem label="电话">
                  <Input v-model="item.phone"></Input>
                </FormItem>
                </Col>
              </Row>

            </Form>
          </div>

        </TabPane>
      </Tabs>

      <div slot="footer">
        <Button
          type="ghost"
          @click="cancel"
        >关闭</Button>
        <Button
          type="primary"
          :loading="modalForm_loading"
          @click="saveForm('modalForm')"
        >保存</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import {
  saveBuilding,
  getAreasCascader,
  areasBuildingsCascader
} from "./../../../api/getData";
import { baseUrl } from "./../../../api/env";
export default {
  props: {
    parentForm: {
      type: Object,
      default: function() {
        return {
          id: "",
          name: "",
          addr: "",
          managerName: "",
          managerMobile: "",
          dutyLetter: "",
          areaGcbd: []
        };
      }
    },
    modalShow: {
      type: Boolean,
      default: true
    },
    modalFormTitle: {
      type: String,
      default: "添加子单位"
    }
  },
  data() {
    return {
      IsModalShow: false,
      modalForm: {},
      modalForm_loading: false,
      deptCasc: [],
      areaGcbdData: [],
      baseServerUrl: baseUrl,
      map: null,
      mousetool: null,
      mapShadeShow: false,
      addrSearchVal: "",
      alarmNotifierList: []
    };
  },
  watch: {
    modalShow(curVal, oldVal) {
      this.modalForm = Object.assign(this.parentForm);

      if (curVal) {
        if (this.parentForm.areaGcbd) {
          this.modalForm.areaGcbd = this.parentForm.areaGcbd
            .split(",")
            .map(function(item) {
              return parseInt(item);
            });
        } else {
          this.modalForm.areaGcbd = [];
        }

        this.addrSearchVal = "";

        this.addMarker(this.modalForm.lng, this.modalForm.lat);

        if (this.modalForm.alarmNotifier) {
          let alarmNotifier = this.modalForm.alarmNotifier;
          let notifierArr = [];
          alarmNotifier.split("|").forEach(item => {
            let name = item.split(",")[0];
            let phone = item.split(",")[1];
            notifierArr.push({ name: name, phone, phone });
          });
          this.alarmNotifierList = notifierArr;
        } else {
          this.alarmNotifierList = [];
        }
      }
      this.IsModalShow = curVal;
    }
  },
  created() {},
  mounted() {
    this.getAreasBuildingsCascader();
    this.initMap();
  },
  methods: {
    async getDeptCascList() {
      let res = await getAreasCascader({ id: 0 });
      this.deptCasc = res.data;
      //console.log(this.deptCasc);
    },
    cancel() {
      this.$emit("listenModalForm");
    },
    async getAreasBuildingsCascader() {
      let res = await areasBuildingsCascader({ allData: false });
      if (res.code == 0) {
        this.areaGcbdData = res.data;
      }
    },
    saveForm(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          this.modalForm_loading = true;
          const params = this.modalForm;
          let arr = this.modalForm.areaGcbd;
          params.areaGcbd = arr.join(",");
          if (this.alarmNotifierList.length > 0) {
            params.alarmNotifier = this.alarmNotifierList.filter(val => val.name&&val.phone)
              .map(item => {
                return item.name + "," + item.phone;
              })
              .join("|");
          }
          //params.departmentId = arr[arr.length-1];
          try {
            let result = await saveBuilding(params);

            if (result.code == "0") {
              this.$Message.success("提交成功!");
              this.$emit("listenModalForm");
              this.$emit("refreshTableList");
            } else {
              this.$Message.error(result.msg);
            }
          } catch (err) {
            console.log(err);
            this.$Message.error("服务器异常，稍后再试");
          }
          this.modalForm_loading = false;
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    },
    initMap() {
      var _this = this;
      this.map = new AMap.Map("map-container", {
        resizeEnable: true,
        scrollWheel: true,
        zoom: 18
      });

      this.map.plugin(["AMap.MouseTool"], function() {
        //鼠标工具插件
        _this.mousetool = new AMap.MouseTool(_this.map);
      });

      var mapEvent2 = AMap.event.addListener(_this.mousetool, "draw", function(
        e
      ) {
        var drawObj = e.obj;
        var point = drawObj.getPosition();
        _this.modalForm.lat = point.lat;
        _this.modalForm.lng = point.lng;
        _this.mapShadeShow = false;
        _this.mapShadeShow = false;
        _this.mousetool.close(false);
      });

      AMap.plugin("AMap.Autocomplete", function() {
        // 实例化Autocomplete
        var autoOptions = {
          // input 为绑定输入提示功能的input的DOM ID
          input: "tipinput"
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        // 无需再手动执行search方法，autoComplete会根据传入input对应的DOM动态触发search
        AMap.event.addListener(autoComplete, "select", function(data) {
          //TODO 选择后的处理程序，data的格式见 附录
          console.log(data);
          if (data.poi.address.length > 0) {
            _this.addrSearchVal =
              data.poi.district + data.poi.address + data.poi.name;
          } else {
            _this.addrSearchVal = data.poi.district + data.poi.name;
          }
          let location = data.poi.location;
          if (location) {
            _this.addMarker(location.lng, location.lat);
            _this.modalForm.lat = location.lat;
            _this.modalForm.lng = location.lng;
          }
        });
      });
    },
    searchAddr() {
      var addr = this.addrSearchVal;
      let _this = this;
      AMap.plugin("AMap.Geocoder", function() {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        });

        geocoder.getLocation(addr, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            // result中对应详细地理坐标信息
            var location = result.geocodes[0].location;
            try {
              if (location) {
                _this.addMarker(location.lng, location.lat);
                _this.modalForm.lat = location.lat;
                _this.modalForm.lng = location.lng;
              } else {
                this.$Message.error("未查询到地理信息!");
              }
            } catch (error) {
              this.$Message.error("查询地理信息失败,请检查网络!");
            }
          } else {
            this.$Message.error("未查询到地理信息!");
          }
        });
      });
    },
    addMarker(lng, lat) {
      this.map.clearMap();
      if (lat && lng) {
        var marker = new AMap.Marker({
          position: [lng, lat]
        });
        marker.setMap(this.map);
        this.map.setFitView();
      }
    },
    startLocate() {
      this.map.clearMap();
      this.mapShadeShow = true;
      this.mousetool.marker({ offset: new AMap.Pixel(-14, -11) });
    },
    addNotifier() {
      if (this.alarmNotifierList.length < 8) {
        this.alarmNotifierList.push({ name: "", phone: "" });
      }
    }
  }
};
</script>
<style lang="less" scoped>
#map-container {
  width: 100%;
  height: 380px;
}
#mapShade {
  width: 100%;
  height: 380px;
  background-color: #000000;
  position: absolute;
  opacity: 0.35;
  left: 0;
  top: 0;
  z-index: 100;
  -webkit-pointer-events: none;
  -moz-pointer-events: none;
  -ms-pointer-events: none;
  -o-pointer-events: none;
  pointer-events: none;
}
.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  -webkit-appearance: button;
  cursor: pointer;
}

.btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}

.btn:hover {
  text-decoration: none;
}

.input-item {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-align: center;
  align-items: center;
  width: 100%;
  height: 3rem;
}

.input-item:last-child {
  margin-bottom: 0;
}

.input-item > select,
.input-item > input[type="text"],
.input-item > input[type="date"] {
  position: relative;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  width: 1%;
  margin-bottom: 0;
}

.input-item > select:not(:last-child),
.input-item > input[type="text"]:not(:last-child),
.input-item > input[type="date"]:not(:last-child) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.input-item > select:not(:first-child),
.input-item > input[type="text"]:not(:first-child),
.input-item > input[type="date"]:not(:first-child) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.input-item-prepend {
  margin-right: -1px;
}

.input-item-text,
input[type="text"],
input[type="date"],
select {
  height: calc(2.2rem + 2px);
}

.input-item-text {
  width: 6rem;
  text-align: justify;
  padding: 0.4rem 0.7rem;
  display: inline-block;
  text-justify: distribute-all-lines;
  /*ie6-8*/
  text-align-last: justify;
  /* ie9*/
  -moz-text-align-last: justify;
  /*ff*/
  -webkit-text-align-last: justify;
  /*chrome 20+*/
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 0;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #495057;
  text-align: center;
  white-space: nowrap;
  background-color: #e9ecef;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
}

.input-item-text input[type="checkbox"],
.input-item-text input[type="radio"] {
  margin-top: 0;
}

.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}

.input-text {
  line-height: 2rem;
  margin-right: 2rem;
}

.info hr {
  margin-right: 0;
  margin-left: 0;
  border-top-color: grey;
}

.info {
  padding: 0.75rem 1.25rem;
  margin-bottom: 1rem;
  border-radius: 0.25rem;
  position: fixed;
  top: 1rem;
  background-color: white;
  width: auto;
  min-width: 22rem;
  border-width: 0;
  right: 1rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
}

.code {
  left: 1.5rem;
  right: 1.5rem;
  top: 1.5rem;
  bottom: 1.5rem;
  overflow: auto;
  margin-bottom: 0rem;
}

.code .btn {
  top: 1rem;
  position: absolute;
  right: 1rem;
}

.code .result {
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 0.5rem;
  padding: 1rem;
  bottom: 1rem;
  position: absolute;
  top: 5.5rem;
  right: 1rem;
  left: 1rem;
  overflow: auto;
}

.code .status {
  color: #80adff;
  display: inline-block;
  font-size: 14px;
}

.code h4 {
  display: inline-block;
  max-width: 20rem;
  margin-right: 1rem;
  margin-bottom: 1rem;
}

select,
input[type="text"],
input[type="date"] {
  display: inline-block;
  width: 100%;
  padding: 0.375rem 1.75rem 0.375rem 0.75rem;
  line-height: 1.5;
  color: #495057;
  vertical-align: middle;
  background: #fff
    url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E")
    no-repeat right 0.75rem center;
  background-size: 8px 10px;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

input[type="text"],
input[type="date"] {
  background: #fff;
  padding: 0.375rem 0.75rem;
}

select:focus,
input[type="text"]:focus,
input[type="date"]:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.1rem rgba(128, 189, 255, 0.1);
}

.btn:focus {
  outline: 0;
  box-shadow: none;
}

select:focus::-ms-value,
input[type="text"]:focus::-ms-value,
input[type="date"]:focus::-ms-value {
  color: #495057;
  background-color: #fff;
}
</style>
